package com.kai.steering.data.service.ctl;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/picture")
@Api(tags = "图片 API")
public class PictureController {
    @Value("${file.picturePath}")
    String picturePath;

    @GetMapping("/image/{imagePath}")
    public ResponseEntity<Resource> getImage(@PathVariable("imagePath") Serializable imagePath) {
        // 转换路径为Path对象
        String ACTUAL_PATH=picturePath+imagePath;

        Path imageFilePath = Paths.get(ACTUAL_PATH);

        // 检查文件是否存在
        if (!Files.exists(imageFilePath)) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        try {
            Resource resource = new FileSystemResource(imageFilePath);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String contentType = Files.probeContentType(imageFilePath);
            headers.setContentType(MediaType.parseMediaType(contentType));

            // 返回图片资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(imageFilePath))
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


    @PostMapping("/image")
    public ResponseEntity<Resource> getImageByPath(@RequestBody Map dataMap) {
        // 转换路径为Path对象
        String imagePath = dataMap.get("imagePath").toString();
        Path imageFilePath = Paths.get(imagePath);

        // 检查文件是否存在
        if (!Files.exists(imageFilePath)) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        try {
            Resource resource = new FileSystemResource(imageFilePath);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String contentType = Files.probeContentType(imageFilePath);
            headers.setContentType(MediaType.parseMediaType(contentType));

            // 返回图片资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(imageFilePath))
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
